package com.tongtong.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tongtong.common.WebConstants;
import com.tongtong.utils.ChannelUtilsV2;
import com.ttio.config.TTNettySocket;
import com.ttio.netty.utils.ChannelUtils;
import com.ttio.server.handler.MessageSocketHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * 启动netty socket @author zl
 */
@Slf4j
@Component
public class SocketStartNettyConfig implements MessageSocketHandler {
    private Integer port = 40600;

    @PostConstruct
    public void startServer() throws Exception {
        TTNettySocket ttNettySocket = new TTNettySocket(port,this);
        ttNettySocket.startNetty();

    }


    @Override
    public void channelAddHandler(ChannelHandlerContext ctx) {
        String key = ChannelUtils.getChannelKey(ctx.channel());
        log.info("用户{}连接成功", key);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, JSONObject jsonObject) {
        String key = ChannelUtils.getChannelKey(ctx.channel());
        log.info("发送用户为{},消息内容为{}",key,jsonObject.getJSONObject("data"));
        if (jsonObject.getJSONObject("data").get("type").equals("regist")) {
            ChannelUtils.setChannelExtend(ctx.channel(), jsonObject.getStr("data"));
            WebConstants.userMap.put(key, jsonObject.getJSONObject("data"));
        } else {
            /*推送消息给其他人*/
            Map<String,Object> data = JSONUtil.toBean(jsonObject.getJSONObject("data"), Map.class);
            ChannelUtilsV2.sendRoomOtherChannel(key, data);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        log.info("用户{}断开连接成功", ctx);
    }


    @Override
    public boolean loginAuthHandler(Channel channel, String token) {
        log.info("token:" + token);
        return true;
    }
}
